package hgx.spring.cloud.lession.productrepertory.hystrix;/**
 * Created by liujun on 2018/4/21.
 */

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;

import java.util.Random;

import hgx.spring.cloud.lession.productrepertory.api.ProductRepository;
import hgx.spring.cloud.lession.productrepertory.vo.ProductVo;
import hgx.spring.cloud.lession.productrepertory.vo.ReponseProductVo;

/**
 * 查询所有产品
 * @author hugx
 * @create 2018-04-21 10:31
 */
public class ProductCreateHystrixCommand extends HystrixCommand<ReponseProductVo> {
    private ProductRepository productRepository;
    private ProductVo productVo;
    private static Random random = new Random();
    private static final  HystrixCommandKey FindAll_Key=HystrixCommandKey.Factory.asKey("product_create");

    public ProductCreateHystrixCommand(ProductRepository productRepository,ProductVo productVo) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(ProductCommandEnum.Product_Get_Set_GroupKey.getKey())).andCommandKey(FindAll_Key));
        this.productRepository = productRepository;
        this.productVo=productVo;
    }


    @Override
    protected ReponseProductVo run() throws Exception {
        long startTime = System.currentTimeMillis();
        int sleepTime = random.nextInt(1000);
        System.out.println("执行 断路器命令的run() 方法 , sleepTime: " + sleepTime + "  , keyName: " + getCommandKey().name());

        ReponseProductVo reponse = new ReponseProductVo();
        boolean flag = productRepository.createPorduct(this.productVo);
        if (flag) {
            reponse.setProductVo(this.productVo);
            reponse.success();
            ProductGetByIdHystrixCommand.flushCache(this.productVo.getId());
//            ProductFindAllHystrixCommand.flushCache();
        }

        System.out.println("3: ----------------run() ,耗时: " + (System.currentTimeMillis() - startTime));
        return reponse;
    }

    @Override
    protected ReponseProductVo getFallback() {
        System.out.println("3.1: ----------------getFallback()  ");
        ReponseProductVo reponse = new ReponseProductVo();
        return reponse;
    }


}
